import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import { Button } from 'antd'
import { connect } from 'dva'
import { nanoid } from 'nanoid'
import { useState } from 'react'

import { deleteRoleApi, queryRoleTreeApi } from '@/api/sys/roleManage'
import AekLinkButton from '@/components/AekLinkButton'
import AekTable from '@/components/AekTable'
import AekTree from '@/components/AekTree'
import Ellipsis from '@/components/Ellipsis'
import PageLayout from '@/components/PageLayout'
import { namespace } from '@/models/sys/roleManage'
import { getPagination, message, modal } from '@/utils/antdHelper'
import { getBasicFn } from '@/utils/dvaUtil/index'
import { requestWithTry } from '@/utils/request'

import EditModal from './components/EditModal'
import SetPermissionsDrawer from './components/SetPermissionsDrawer'
import styles from './index.module.less'

/** 系统 - 角色管理 */
const Index = ({ modelState, loading }) => {
  const { pageList, pagination, searchParams } = modelState
  const { toAction, getLoading } = getBasicFn({ namespace, loading })

  const [reloadKey, setReloadKey] = useState(nanoid())

  const add = async () => {
    await EditModal.PromiseThen()
    message.success('新增成功')
    setReloadKey(nanoid())
  }

  const edit = async row => {
    await EditModal.PromiseThen({
      row,
    })
    message.success('修改成功')
    setReloadKey(nanoid())
  }

  const remove = async ({ roleId, roleName }) => {
    modal.confirm({
      title: `确认删除角色【${roleName}】？`,
      onOk: async () => {
        await requestWithTry(deleteRoleApi, { roleId })
        message.success('删除成功')
        setReloadKey(nanoid())
      },
    })
  }

  const setPermissions = async row => {
    await SetPermissionsDrawer.PromiseThen({
      row,
    })
    message.success('修改成功')
  }

  const removeUser = async ({ id, fullName, userName }) => {
    modal.confirm({
      title: `确认将账户【${fullName}】从【${userName}】移除？`,
      onOk: async () => {
        await requestWithTry(deleteRoleApi, { id })
        message.success('删除成功')
        if ((pagination.current - 1) * pagination.pageSize === pagination.total - 1) {
          toAction('getPageList', { current: pagination.current - 1 || 1 })
        } else {
          toAction('getPageList')
        }
      },
    })
  }

  /** @type {import("@/components/AekTree").AekTreeProps} */
  const treeProps = {
    api: queryRoleTreeApi,
    fieldNames: {
      key: 'roleId',
      title: 'roleName',
    },
    canCancelSel: false,
    defaultSelectFirst: true,
    onSelect: (_, selectedRows) => {
      const { organizationId, roleId } = selectedRows.node
      toAction({
        searchParams: { organizationId, roleId },
        pagination: { ...pagination, current: 1 },
      })
      toAction('getPageList')
    },
    contentRender: data => {
      data.forEach(item => {
        item.selectable = false
      })
      return data
    },
    titleRender: item => (
      <div className={`flex ${styles.role}`}>
        <Ellipsis>{item.roleName}</Ellipsis>
        <div
          className={`ml20px flex-none ${styles.opera}`}
          onClick={e => {
            e.stopPropagation?.()
          }}
        >
          <a onClick={() => setPermissions(item)}>权限</a>
          <EditOutlined className='ml10px c-primary' type='edit' onClick={() => edit(item)} />
          <DeleteOutlined
            className='ml10px c-del'
            type='delete'
            onClick={() => {
              remove(item)
            }}
          />
        </div>
      </div>
    ),
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    configKey: namespace,
    rowKey: 'userId',
    loading: getLoading('getPageList'),
    dataSource: pageList,
    pagination: getPagination(pagination, (current, pageSize) => {
      toAction('getPageList', { current, pageSize })
    }),
    columns: [
      { dataIndex: 'fullName', title: '姓名' },
      { dataIndex: 'userName', title: '用户名' },
      { dataIndex: 'mobileNumber', title: '联系方式' },
      { dataIndex: 'jobNumber', title: '工号' },
      { dataIndex: 'departmentName', title: '科室' },
      {
        key: 'operate',
        title: '操作',
        fixed: 'right',
        width: 100,
        className: 'text-center!',
        render: (_, row) => (
          <AekLinkButton danger onClick={() => removeUser(row)}>
            移除
          </AekLinkButton>
        ),
      },
    ],
  }

  return (
    <PageLayout>
      <PageLayout.Columns>
        <PageLayout.LeftColumn>
          <Button type='primary' block className='mb10px' onClick={add}>
            新增角色
          </Button>
          <AekTree reloadKey={reloadKey} {...treeProps} />
        </PageLayout.LeftColumn>
        <PageLayout.RightColumn>
          <AekTable {...tableProps} />
        </PageLayout.RightColumn>
      </PageLayout.Columns>
    </PageLayout>
  )
}

export default connect(store => ({
  modelState: store[namespace],
  loading: store.loading,
}))(Index)
